package com.crm.system.service.impl.contactManager;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.beust.jcommander.internal.Lists;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatisticalPeriodEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.DateUtils;
import com.crm.common.util.ESUtil;
import com.crm.model.dto.InsertCardCallable;
import com.crm.model.dto.InsertContactCallable;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.cluePoolManager.ClueVisitRecord;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactExchangeCode;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerContactPerson;
import com.crm.model.entity.customerManager.CustomerProductDetailMemberCard;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.entity.systemManager.SysParameterSetting;
import com.crm.model.qo.cluePoolManager.ClueFollowQO;
import com.crm.model.qo.contactManager.ContactFollowPlanTimeQO;
import com.crm.model.qo.contactManager.ContactQO;
import com.crm.model.vo.contactManager.*;
import com.crm.model.vo.customerManager.CustomerContactVO;
import com.crm.model.vo.customerManager.CustomerProductDetailMemberCardRawDataVO;
import com.crm.model.vo.customerManager.CustomerVO;
import com.crm.model.vo.customerManager.FzCustomerContactVO;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.model.vo.systemManager.CardImportVO;
import com.crm.model.vo.systemManager.ContactImportVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.cluePoolManager.ClueVisitRecordDbService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.customerManager.*;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.system.service.contactManager.ContactInformationService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.impl.cluePoolManager.ClueFollowServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * bj
 * 联系人管理信息
 */
@Service
@Slf4j
public class ContactServiceImpl implements ContactService {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    private ContactDbService contactDbService;

    @Autowired
    private CustomerPoolDbService customerPoolDbService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    private CustomerContactPersonDbService customerContactPersonDbService;

    @Autowired
    private ContactInformationService contactInformationService;

    @Autowired
    private ContactInformationDbService contactInformationDbService;

    @Autowired
    private ClueFollowDbService clueFollowDbService;

    @Autowired
    private ClueVisitRecordDbService clueVisitRecordDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    @Autowired
    ImportFailureLogDbService importFailureLogDbService;

    @Autowired
    SysCompanyDbService sysCompanyDbService;

    @Autowired
    CustomerContractDbService customerContractDbService;

    @Autowired
    SingleProductCustomerDbService singleProductCustomerDbService;

    @Autowired
    SingleProductCustomerContactDbService singleProductCustomerContactDbService;

    @Autowired
    CustomerProductDetailMemberCardDbService customerProductDetailMemberCardDbService;

    @Autowired
    CustomerProductOrderDbService customerProductOrderDbService;

    @Autowired
    FinishOrderDBservice finishOrderDBservice;


    private static final String FOLLOW_QUERY_TYPE = "followTimes";

    private static final String CONTACT_QUERY_TYPE = "newContact";


    /**
     * 联系人管理信息
     *
     * @param pageIndex 页码
     * @param pageSize  分页大小
     * @param contactQO 查询条件
     * @param sortName  排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @return
     */
    @Override
    public DhPageInfo<ContactVO> selectContactVOList(Integer pageIndex, Integer pageSize, ContactQO contactQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);

        //增加删除状态查询条件(0:正常;1:已删除)
        contactQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(contactQO.getDateType())) {
            if ("thisWeek".equals(contactQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(contactQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYearMonth".equals(contactQO.getDateType())) {
                //按照年度月份查询
                contactQO.setMonth(year+"-"+contactQO.getMonth());
                dateUnit = 3;
            }
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("a.create_tm ").append(sortOrder);
                }
                break;
                case "thermodynamicValue": {
                    order.append("a.thermodynamic_value ").append(sortOrder);
                }
                break;
                case "followTm": {
                    order.append("followTm ").append(sortOrder);
                }
                break;
                case "followPlanTime": {
                    order.append("a.follow_plan_time ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }

        if(!StringUtils.isBlank(contactQO.getTabType())) {
            if("1".equals(contactQO.getTabType())){
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DAY_OF_MONTH, -7);
                String endDate = new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
                contactQO.setDate(endDate);
            }
            if("2".equals(contactQO.getTabType())) {
                Calendar now = Calendar.getInstance();
                now.add(Calendar.DAY_OF_MONTH, -30);
                String endDate = new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
                contactQO.setDate(endDate);
            }
            if("3".equals(contactQO.getTabType())) {
                Calendar now = Calendar.getInstance();
                String endDate = new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
                contactQO.setDate(endDate);
            }
        }

        List<ContactVO> contactList = new ArrayList<ContactVO>();
        if ("0".equals(contactQO.getBs())) {
            if (rs) {
                //超级管理员
                contactList = contactDbService.selectContactGlyList(contactQO, dateUnit, order.toString());
            } else {
                //普通管理员
                contactQO.setCompanyId(userAccount.getCompanyId());
                contactList = contactDbService.selectContactFgsList(contactQO, dateUnit, order.toString());
            }
        } else {
            //普通用户
            contactQO.setCompanyId(userAccount.getCompanyId());
            contactQO.setAccountId(userAccount.getAccountId());
            contactList = contactDbService.selectContactPtyhList(contactQO, dateUnit, order.toString());
        }


        PageInfo<ContactVO> pageInfo = new PageInfo<ContactVO>(contactList);
        return new DhPageInfo<ContactVO>(pageInfo, contactList);
    }

    /**
     * 联系人-新增联系人  联系人大表和客户下联系人同时新增
     *
     * @param customerContactVO 联系人实体类
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String addContact(CustomerContactVO customerContactVO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean result = false;
        String contactId = "";
        String customerId = CommonUtils.getGUID();
        String contactInformationId = CommonUtils.getGUID();

        String info = customerContactVO.getContactInformation().replaceAll("-", "");

        if(!StringUtils.isBlank(customerContactVO.getExtNumber())) {

            customerContactVO.setContactInformation(customerContactVO.getContactInformation().replaceAll("-","") + " - " + customerContactVO.getExtNumber());
        }else{
            customerContactVO.setContactInformation(customerContactVO.getContactInformation().replaceAll("-",""));
        }

        //customerContactVO.setContactInformation(customerContactVO.getContactInformation());

        /*if ("1".equals(customerContactVO.getContactNature())) {
            customerContactVO.setCustomerId(customerId);
        }*/
        if (!StringUtils.isBlank(customerContactVO.getContactId())) {  //有值
            //新增联系方式
            result = addContactIn(customerContactVO, contactInformationId, userAccount);
        } else {
            contactId = CommonUtils.getGUID();
            Contact contact = new Contact();
            contact.setContactId(contactId);
            contact.setContactName(customerContactVO.getContactName());
            contact.setContactPosition(customerContactVO.getContactPosition());
            contact.setContactInformation(customerContactVO.getContactInformation());
            contact.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
            contact.setProvinceId(customerContactVO.getProvinceId());
            contact.setProvinceName(customerContactVO.getProvinceName());
            contact.setCityId(customerContactVO.getCityId());
            contact.setCityName(customerContactVO.getCityName());
            contact.setIndustry(customerContactVO.getIndustry());
            contact.setCompanyAddress(customerContactVO.getCompanyAddress());
            contact.setWx(customerContactVO.getWx());
            contact.setMailBox(customerContactVO.getMailBox());
            contact.setCurrentIntention(customerContactVO.getCurrentIntention());
            contact.setFollowUpTimes(0);
            contact.setCreatePeopleId(userAccount.getAccountId());
            contact.setCreateTm(new Date());
            contact.setUpdatePeopleId(userAccount.getAccountId());
            contact.setUpdateTm(new Date());
            contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            contact.setContactState(customerContactVO.getContactState());
            contact.setMemberGrade(customerContactVO.getMemberGrade());
            //contact.setMergeState(Integer.parseInt(customerContactVO.getMergeState()));
            if(StringUtils.isNotBlank(customerContactVO.getContactNature())){
                contact.setContactNature(Integer.parseInt(customerContactVO.getContactNature()));
            }
            contact.setHomeAddress(customerContactVO.getHomeAddress());
            contact.setGender(customerContactVO.getGender());
            contact.setBirthDate(customerContactVO.getBirthDate());
            contact.setCompanyName(customerContactVO.getCompanyName());
            contact.setAbolishState(1);
            contact.setIsCreate(0);
            if ("0".equals(customerContactVO.getContactNature())) {
                contact.setCustomerId(customerContactVO.getCustomerId());
            } else {
                /*Customer customer = new Customer();
                customer.setCustomerId(customerId);
                customer.setCustomerName(customerContactVO.getContactName());
                customer.setCustomerNumber(createCustomerNumber());
                customer.setCustomerType("1"); //个人客户
                customer.setContactPersonPhone(customerContactVO.getContactInformation());
                customer.setDetailedAddress(customerContactVO.getCompanyAddress());
                customer.setCompanyName(userAccount.getCompanyId());
                customer.setProvinceCode(customerContactVO.getProvinceId());
                customer.setProvinceName(customerContactVO.getProvinceName());
                customer.setCityCode(customerContactVO.getCityId());
                customer.setCityName(customerContactVO.getCityName());
                customer.setAccountId(userAccount.getAccountId());
                customer.setCreatePeopleId(userAccount.getAccountId());
                customer.setOwnerId(userAccount.getAccountId());
                customer.setCurrentStatus(Short.parseShort("3"));
                customer.setCreateTm(new Date());
                customer.setUpdatePeopleId(userAccount.getAccountId());
                customer.setUpdateTm(new Date());
                customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                //查询全国默认池 客户的
                CustomerPool customerPool = customerPoolDbService.selectCustomerPoolByName("全国默认池");
                if (customerPool != null) {
                    customer.setCustomerPoolId(customerPool.getCustomerPoolId());
                }
                customerDbService.insertCustomer(customer);

                //syncES(customer,userAccount.getAccountId(),"联系人管理-新建个人客户");

                contact.setCustomerId(customerId);*/
            }

            contact.setAccountId(userAccount.getAccountId());
            contact.setCompanyId(userAccount.getCompanyId());
            //新增联系人管理的联系人
            result = contactDbService.addContact(contact);


            customerContactVO.setContactId(contactId);

            addContactIn(customerContactVO, contactInformationId, userAccount);

            //if ("0".equals(customerContactVO.getContactNature())) {
            //新增客户下的联系人
            if("0".equals(customerContactVO.getContactNature())) {
                CustomerContactPerson customerContactPerson = new CustomerContactPerson();
                String customerContactPersonId = CommonUtils.getGUID();
                customerContactPerson.setCustomerContactPersonId(customerContactPersonId);
                customerContactPerson.setContactName(customerContactVO.getContactName());
                customerContactPerson.setContactPosition(customerContactVO.getContactPosition());
                customerContactPerson.setContactInformation(customerContactVO.getContactInformation());
                customerContactPerson.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
                customerContactPerson.setIsSeniorExecutive(customerContactVO.getIsSeniorExecutive());
                customerContactPerson.setMailBox(customerContactVO.getMailBox());
                customerContactPerson.setWx(customerContactVO.getWx());
                customerContactPerson.setFollowUpTimes(0);
                customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
                customerContactPerson.setCreateTm(new Date());
                customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                customerContactPerson.setUpdateTm(new Date());
                customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                customerContactPerson.setAbolishState(1);
                customerContactPerson.setContactState(customerContactVO.getContactState());
                customerContactPerson.setMergeState(Integer.parseInt(customerContactVO.getMergeState()));
                customerContactPerson.setCustomerId(customerContactVO.getCustomerId());
                customerContactPerson.setCompanyId(userAccount.getCompanyId());
                //新增客户下的联系人
                Boolean rs = customerPoolDbService.addCustomerContactPerson(customerContactPerson);
            }

                /*//联系人类型    主联系人-1   从联系人-2  目前意向   0有意向 1无意向
                if (1 == customerContactVO.getContactState() && "0".equals(customerContactVO.getCurrentIntention())) {
                    Customer customers = customerDbService.selectCustomerById(customerContactVO.getCustomerId());
                    if (!"1".equals(customers.getPotentialCustomers())) {
                        customers.setPotentialCustomers(1);  //  意向客户---0:无意向客户;1: 意向客户
                        customers.setUpdatePeopleId(userAccount.getAccountId());
                        customers.setUpdateTm(new Date());
                        customers.setAccountId(userAccount.getAccountId());
                        customerPoolDbService.updateCustomer(customers);
                    }
                }*/
            // }

            result = true;
        }

        if (result) {
            //contactSendCode(info,userAccount.getAccountId(),contactId,"1");
            return contactId;
        } else {
            return "";
        }


    }

    /**
     * 手机号发码
     * @param contactInformation 手机号
     * @param accountId 用户id
     * @param contactId 联系人id
     * @param bs 0个人客户传过来的   1其他入口
     * @return
     */
    @Override
    public String contactSendCode(String contactInformation,String accountId,String contactId,String bs) {
        String msg = "手机号格式不正确!";
        SysParameterSetting sysParameterSetting = contactDbService.selectContactCodeStatus();
        if(sysParameterSetting != null) {
            if(sysParameterSetting.getContactCodeStatus() == 0) {
                HashMap<String, Object> paramMap = new HashMap<>();

                String substring = contactInformation.substring(0, 1);
                if("0".equals(substring)) {
                    contactInformation = contactInformation.substring(1,contactInformation.length());
                }

                String regex = "^1[3|4|5|6|7|8|9][0-9]{9}$";
                if(contactInformation.length() == 11){
                    Pattern p = Pattern.compile(regex);
                    Matcher m = p.matcher(contactInformation);
                    boolean isMatch = m.matches();
                    if(isMatch){
                        paramMap.put("phone", contactInformation);
                        log.info("请求数据---"+paramMap);
                        //String res= HttpUtil.post("http://api.nsrjlb.com/crm/ExchangeCode/activity_20210806", paramMap);
                        String res= HttpUtil.post("https://api.nsrjlb.com/crm/ExchangeCode/activity_20210918", paramMap);
                        log.info("返回数据---"+res);
                        JSONObject json = JSON.parseObject(res);
                        Integer de = json.getInteger("code");
                        msg = json.getString("msg");
                        if(de == 1) {
                            String data = json.getString("data");
                            CodeVO code = JSONArray.parseObject(data, CodeVO.class);

                            ContactExchangeCode exchangeCode = contactDbService.selectContactExchangeCodeByInformationAndCode(contactInformation,code.getCode());
                            if(exchangeCode == null) {
                                ContactExchangeCode contactExchangeCode = new ContactExchangeCode();
                                contactExchangeCode.setExchangeCodeId(CommonUtils.getGUID());
                                contactExchangeCode.setExchangeCode(code.getCode());
                                contactExchangeCode.setCreatePeopleId(accountId);
                                contactExchangeCode.setCreateTm(new Date());
                                contactExchangeCode.setUpdatePeopleId(accountId);
                                contactExchangeCode.setUpdateTm(new Date());
                                contactExchangeCode.setContactId(contactId);
                                contactExchangeCode.setContactInformation(contactInformation);
                                contactExchangeCode.setMsg(msg);
                                contactExchangeCode.setCodeStatus(code.getSendMessage());
                                contactDbService.addContactExchangeCode(contactExchangeCode);

                                Contact contact = contactDbService.selectContactById(contactId);
                                if("1".equals(bs)) {
                                    contact.setIsSendCode(1);
                                    contact.setUpdatePeopleId(accountId);
                                    contact.setUpdateTm(new Date());
                                    contactDbService.updateContact(contact);
                                }else{
                                    return "0";
                                }

                            }
                        }
                    }else{
                        log.info("手机号"+contactInformation +"格式不正确!");
                    }
                }
            }else{
                msg = "活动已关闭!";
            }
        }
        return msg;
    }

    /**
     * 查询系统设置表
     * @return
     */
    @Override
    public SysParameterSetting selectParameterSetting() {
        return contactDbService.selectContactCodeStatus();
    }

    /**
     * 会员卡数据补全
     */
    @Override
    public void cardDataCompletion() throws ParseException {
        Map<String,Object> map = new HashMap<>();

        //查询所有的会员卡数据
        List<CustomerProductDetailMemberCardRawDataVO> rawList = customerProductDetailMemberCardDbService.selectCardDataRaw();

        //查询会员卡没有合同id的
        List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectCardData();
        for(CustomerProductDetailMemberCard card : cardList) {
            map.put(card.getMemberCardNumber(),card);
        }

        if (rawList.size() > 0){
            int count = 1000;                   //一个线程处理1000条数据
            int listSize = rawList.size();        //数据集合大小
            int runSize = (listSize/count)+1;  //开启的线程数
            //int runSize = importExportService.calculateImportedThreads(listSize);

            List<CustomerProductDetailMemberCardRawDataVO> newlist = null;       //存放每个线程的执行数据

            ExecutorService executor = Executors.newCachedThreadPool();
            //创建两个个计数器
            CountDownLatch begin = new CountDownLatch(1);
            CountDownLatch end = new CountDownLatch(runSize);
            List<FutureTask<JSONObject>> taskList = new ArrayList<FutureTask<JSONObject>>();
            for (int i = 0; i < runSize ; i++) {
                //计算每个线程执行的数据
                if ((i + 1) == runSize) {
                    int startIndex = (i * count);
                    int endIndex = rawList.size();
                    newlist = rawList.subList(startIndex, endIndex);
                } else {
                    int startIndex = (i * count);
                    int endIndex = (i + 1) * count;
                    if (endIndex > rawList.size()){
                        endIndex = rawList.size();
                    }
                    newlist = rawList.subList(startIndex, endIndex);
                }
                FutureTask<JSONObject> futureTask = new FutureTask(new InsertCardCallable(
                        sysCompanyDbService, userAccountDbService,
                        customerDbService,customerContractDbService,
                        customerProductOrderDbService,finishOrderDBservice,
                        customerProductDetailMemberCardDbService,
                        newlist, map,begin, end));
                taskList.add(futureTask);
                executor.submit(futureTask);//submit返回一个Future，代表了即将要返回的结果
            }

            //重复的行数
            List<Integer> repeatIdList = new ArrayList();
            //失败行数
            List<Integer> importFailIdList = new ArrayList();

            for (int i = 0; i < taskList.size(); i++) {
                try {

                    //合同编号为空的条数
                    JSONArray repeatIdArray = taskList.get(i).get().getJSONArray("repeatIdStr");
                    for (int j = 0; j < repeatIdArray.size(); j++){
                        int repeat = Integer.parseInt(repeatIdArray.get(j).toString());
                        repeatIdList.add(repeat + i*100);
                    }

                    //成功的条数
                    JSONArray importFailIdArray = taskList.get(i).get().getJSONArray("importFailIdStr");
                    for (int j = 0; j < importFailIdArray.size(); j++){
                        int importFail = Integer.parseInt(importFailIdArray.get(j).toString());
                        importFailIdList.add(importFail + i*100);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            // 关闭线程池
            executor.shutdown();
            log.info("合同编号为空的条数---------"+repeatIdList.size());
            log.info("成功的条数---------"+importFailIdList.size());
        }

    }

    /**
     * 转时间格式
     * @param date 创建时间  结束时间
     * @return
     */
    public Date formatTimeSf(String date) throws ParseException {
        //同一个Excel有不一样的时间格式……
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(date);
    }

    public void cardDataMany() {
        Map<String,Object> map = new HashMap<>();

        //查询所有的会员卡数据
        List<CustomerProductDetailMemberCardRawDataVO> rawList = customerProductDetailMemberCardDbService.selectCardDataRaw();

        //查询会员卡没有合同id的
        List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectCardData();
        for(CustomerProductDetailMemberCard card : cardList) {
            map.put(card.getMemberCardNumber(),card);
        }

        for(CustomerProductDetailMemberCardRawDataVO raw : rawList) {
            if(map.containsKey(raw.getCardNumber())){
                map.remove(raw.getCardNumber());
            }
        }

        for (String key : map.keySet()) {
            log.info("key = " + key + ", value = " + new GsonBuilder().serializeNulls().create().toJson(map.get(key)));
        }
    }

    /**
     * crm会员卡跟本系统会员卡比对
     * @param list
     * @return
     */
    @Override
    public JSONObject importCard(List<CardImportVO> list) {
        Date date = new Date();

        int i = 0;


        Map<String,Object> map = new HashMap<>();

        List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectCardData();
        for(CustomerProductDetailMemberCard card : cardList) {
            map.put(card.getMemberCardNumber(),card);
        }

        for(CardImportVO raw : list) {
            if (!map.containsKey(raw.getCardNumber())) {
                if(!StringUtils.isBlank(raw.getCardNumber())) {
                    CustomerProductDetailMemberCard customerProductDetailMemberCard = customerProductDetailMemberCardDbService.getCustomerProductDetailMemberCard(raw.getCardNumber());
                    if (customerProductDetailMemberCard == null) {

                        CustomerProductDetailMemberCard card = new CustomerProductDetailMemberCard();
                        card.setCustomerProductDetailMemberCardId(CommonUtils.getGUID());
                        card.setMemberCardNumber(raw.getCardNumber());
                        //电子卡密码
                        if (!StringUtils.isBlank(raw.getPassword())) {
                            card.setMemberCardPassword(raw.getPassword());
                        }

                        //订单编号
                        if(!StringUtils.isBlank(raw.getOrderNumber())){
                            CustomerProductOrderVO orderInfoByNumber = customerProductOrderDbService.getOrderInfoByNumber(raw.getOrderNumber());
                            if(orderInfoByNumber != null) {
                                card.setProductOrderId(orderInfoByNumber.getProductOrderId());
                                card.setOrderNumber(orderInfoByNumber.getOrderNumber());
                                card.setCreatePeopleId(orderInfoByNumber.getCreatePeopleId());
                                card.setAccountId(orderInfoByNumber.getCreatePeopleId());

                                List<FinishOrderProduct> finishList = finishOrderDBservice.selectFinishOrderProductList("1","1", orderInfoByNumber.getProductOrderId());
                                if(finishList != null && finishList.size() > 0) {
                                    FinishOrderProduct finishOrderProduct = finishList.get(0);
                                    card.setMemberProductCode(finishOrderProduct.getProductCode());
                                    card.setFinishOrderProductNum(finishOrderProduct.getFinishOrderProductNum());
                                    card.setProductPrice(finishOrderProduct.getProductFinalPrice());
                                }

                                if(!StringUtils.isBlank(orderInfoByNumber.getContractId())) {
                                    CustomerContract contract = customerContractDbService.selectContractById(orderInfoByNumber.getContractId());
                                    if(contract != null) {
                                        card.setContractId(contract.getContractId());
                                        card.setContractNumber(contract.getContractNumber());
                                    }
                                }
                            }



                        }

                        if(!StringUtils.isBlank(raw.getFirms())) {

                            //先看看是不是公司名称
                            SysCompany sysCompany = sysCompanyDbService.selectSysCompanyByName(raw.getFirms());
                            //公司id
                            if(sysCompany != null) {
                                card.setCompanyId(sysCompany.getCompanyId());
                            }else{
                                //看看是不是客户
                                CustomerVO customerVO = customerDbService.selectCustomerByName(raw.getFirms());
                                if(customerVO != null) {
                                    card.setCustomerId(customerVO.getCustomerId());
                                }
                            }
                        }

                        card.setCreateTm(date);
                        card.setUpdateTm(date);
                        card.setDataSource(1);
                        log.info("更新前的内容:"+new GsonBuilder().serializeNulls().create().toJson(card));
                        customerProductDetailMemberCardDbService.addCustomerProductDetailMemberCard(card);
                        i+=1;
                    }
                }

            }
        }
        log.info("条数------"+i);

        return null;
    }

    public void cardDataManys(List<CardImportVO> list) {
        Map<String,Object> map = new HashMap<>();

        //查询所有的会员卡数据
        //List<CustomerProductDetailMemberCardRawDataVO> rawList = customerProductDetailMemberCardDbService.selectCardDataRaw();

        //查询会员卡没有合同id的
        List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectCardData();
        for(CustomerProductDetailMemberCard card : cardList) {
            map.put(card.getMemberCardNumber(),card);
        }

        for(CardImportVO raw : list) {
            if(map.containsKey(raw.getCardNumber())){
                map.remove(raw.getCardNumber());
            }
        }

        for (String key : map.keySet()) {
            log.info("key = " + key + ", value = " + new GsonBuilder().serializeNulls().create().toJson(map.get(key)));
        }
    }

    /**
     * 会员卡数据所有人添加
     * @return
     */
    @Override
    public void cardAccount() {
        int a = 0;
        Date date = new Date();
        //2021-09-02今天这个时间段的
        //List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectTimeEndCardData("2021-09-02 10:16:52","2021-09-02 12:00:00");
        //
        List<CustomerProductDetailMemberCard> cardList = customerProductDetailMemberCardDbService.selectTimeEndCardData("2021-09-02 10:50:52","2021-09-02 11:27:02");
        for(CustomerProductDetailMemberCard  card : cardList) {
            if(StringUtils.isBlank(card.getAccountId())) {
                //通过客户查询accountId
                if(!StringUtils.isBlank(card.getCustomerId())) {
                    Customer customer = customerDbService.selectCustomerById(card.getCustomerId());
                    if(customer != null) {
                        card.setCreatePeopleId(customer.getAccountId());
                        card.setAccountId(customer.getAccountId());
                        card.setUpdatePeopleId(customer.getAccountId());
                        card.setUpdateTm(date);
                    }
                }

                if(!StringUtils.isBlank(card.getContractId())) {
                    CustomerContract customerContract = customerContractDbService.selectContractById(card.getContractId());
                    if(customerContract != null) {
                        card.setCreatePeopleId(customerContract.getCreatePeopleId());
                        card.setAccountId(customerContract.getCreatePeopleId());
                        card.setUpdatePeopleId(customerContract.getCreatePeopleId());
                        card.setUpdateTm(date);
                    }
                }

                if(!StringUtils.isBlank(card.getProductOrderId())) {
                    CustomerProductOrder order = customerProductOrderDbService.selectCustomerProductOrderById(card.getProductOrderId());
                    card.setCreatePeopleId(order.getCreatePeopleId());
                    card.setAccountId(order.getCreatePeopleId());
                    card.setUpdatePeopleId(order.getCreatePeopleId());
                    card.setUpdateTm(date);
                }

                customerProductDetailMemberCardDbService.updateCard(card);
                a+=1;
            }

        }
        log.info("修改条数:" + a);
    }


    public Boolean addContactIn(CustomerContactVO customerContactVO, String contactInformationId, UserAccount userAccount) {
        ContactInformationVO contactInformation = new ContactInformationVO();
        contactInformation.setContactInformationId(contactInformationId);
        contactInformation.setContactInformation(customerContactVO.getContactInformation());
        if (StringUtils.isBlank(customerContactVO.getContactType())) {
            contactInformation.setContactType("单位电话");
        } else {
            contactInformation.setContactType(customerContactVO.getContactType());
        }

        //联系方式类型  0主联系方式 1从联系方式
        contactInformation.setContactInformationType(customerContactVO.getContactInformationType());
        contactInformation.setContactId(customerContactVO.getContactId());
        if(!StringUtils.isBlank(customerContactVO.getCustomerId())) {
            contactInformation.setCustomerId(customerContactVO.getCustomerId());
        }
        contactInformation.setCreatePeopleId(userAccount.getAccountId());
        contactInformation.setCreateTm(new Date());
        contactInformation.setUpdatePeopleId(userAccount.getAccountId());
        contactInformation.setUpdateTm(new Date());
        contactInformation.setAbolishState(1);  //废止状态  1启动 2废止
        contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        contactInformation.setCompanyId(userAccount.getCompanyId());
        Boolean rs = contactInformationService.addContactInformation(contactInformation);
        return rs;
    }

    /**
     * 生成客户编号
     *
     * @return
     */
    public String createCustomerNumber() {
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String newCustomerNumber = datetime + "00001";
        String maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
        if (Objects.nonNull(maxCustomerNumber)) {
            if (maxCustomerNumber.length() < 8) {
                maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
                if (Objects.isNull(maxCustomerNumber)) {
                    return newCustomerNumber;
                }
            }
            if (datetime.equals(maxCustomerNumber.substring(0, 8))) {
                newCustomerNumber = datetime + String.format("%05d", Integer.parseInt(maxCustomerNumber.substring(8)) + 1);
            }
        }
        return newCustomerNumber;
    }

    /**
     * 联系人-新增联系人--同一客户下联系人去重
     *
     * @param customerId         客户id
     * @param contactName        联系人姓名
     * @param contactInformation 联系方式
     * @param contactNature      联系人性质  0企业联系人  1个人联系人
     * @return
     */
    @Override
    public Contact getCustomerIdAndContactNameAndAccountId(String customerId, String contactName, String contactInformation, String contactNature,String csd) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        int mergeState = 0;
        List<Contact> list = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyId(customerId, contactName, contactInformation, contactNature, userAccount.getAccountId(),userAccount.getCompanyId(),csd);
        if (list.size() == 0) {
            return new Contact();
        } else {
            return list.get(0);
        }
    }

    /**
     * 联系人-删除  删除联系人大表和客户下联系人表  逻辑删除
     *
     * @param contactId 联系人id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean deleteContact(String contactId) {

        //查询联系人
        Contact contacts = contactDbService.selectContactById(contactId);

        //获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Contact contact = new Contact();
        contact.setContactId(contactId);
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
        Boolean rs = contactDbService.deleteContactById(contact);
        Boolean res = true;

        if (contacts.getContactNature() == 0) {

            List<ContactInformation> lxfsList = contactInformationDbService.contactInformationList("create_tm desc", contactId);
            for (ContactInformation contactInformation : lxfsList) {
                contactInformation.setUpdatePeopleId(userAccount.getAccountId());
                contactInformation.setUpdateTm(new Date());
                contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                //逻辑删除  联系人下的联系方式
                contactInformationDbService.deleteContactInformationById(contactInformation);
            }


            List<CustomerContactPerson> list = customerDbService.getCustomerIdAndContactName(contacts.getCustomerId(), contacts.getContactName(), contacts.getContactInformation());
            if (list.size() != 0) {
                CustomerContactPerson customerContactPerson = list.get(0);
                customerContactPerson.setCustomerContactPersonId(customerContactPerson.getCustomerContactPersonId());
                customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                customerContactPerson.setUpdateTm(new Date());
                customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                res = customerContactPersonDbService.deleteCustomerContactPersonById(customerContactPerson);
            }
        }


        if (rs == res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过联系人id查询联系人信息 mybatis查询
     *
     * @param contactId 联系人id
     * @return
     */
    @Override
    public Contact selectContactById(String contactId) {
        return contactDbService.selectContactById(contactId);
    }

    /**
     * 通过联系人id查询联系人详情信息
     *
     * @param contactId 联系人id
     * @return
     */
    @Override
    public ContactVO selectContactDetailById(String contactId) {
        /*UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<ContactDetailFollowVO> list = clueFollowDbService.selectFollowByContactId(contactId,0);
        Integer thermodynamicValue =0;
        for(ContactDetailFollowVO contactDetailFollowVO : list){
            //跟进方式  1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
            if(contactDetailFollowVO.getFollowWay() !=0 ){
                //拜访 10分  其他的5分
                if(contactDetailFollowVO.getFollowWay() == 2){
                    thermodynamicValue+=10;
                }else{
                    thermodynamicValue+=5;
                }
            }
        }

        Contact con = new Contact();
        con.setContactId(contactId);
        con.setThermodynamicValue(thermodynamicValue);
        con.setUpdatePeopleId(userAccount.getAccountId());
        con.setUpdateTm(new Date());
        contactDbService.updateContact(con);*/

        ContactVO contactVO = contactDbService.selectContactDetailById(contactId);
        return contactVO;
    }

    /**
     * 联系人-联系人详情-修改联系人详情
     *
     * @param contactId 联系人id
     * @param name      图片  修改联系人评分  标签
     * @param bs        1 上传图片  2修改联系人评分  3标签
     * @return
     */
    @Override
    public Boolean updateContact(String contactId, String name, String bs) {
        Contact tact = contactDbService.selectContactById(contactId);
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (tact == null) {
            return false;
        }
        if ("1".equals(bs)) {
            tact.setUploadId(name);
        }
        if ("2".equals(bs)) {
            tact.setContactRating(name);
        }
        if ("3".equals(bs)) {
            tact.setTag(name);
        }
        tact.setUpdatePeopleId(userAccount.getAccountId());
        tact.setUpdateTm(new Date());
        Boolean rs = contactDbService.updateContact(tact);
        return rs;
    }

    /**
     * 联系人-联系人详情-修改联系人详情  家庭住址,公司地址,微信,邮箱
     * @param contact 联系人信息
     * @return
     */
    @Override
    public Boolean updateContactDetail(Contact contact) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        Boolean rs = contactDbService.updateContact(contact);
        return rs;
    }

    /**
     * 展示兑换码列表
     * @param pageIndex 页码
     * @param pageSize 条数
     * @param sortName 分组名称
     * @param sortOrder 分组类型
     * @param contactId 联系人id
     * @return
     */
    @Override
    public DhPageInfo<ContactExchangeCodeVO> selectContactExchangeCodeList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String contactId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<ContactExchangeCodeVO> list = contactDbService.selectContactExchangeCodeList(contactId, "create_tm desc");
        PageInfo<ContactExchangeCodeVO> pageInfo = new PageInfo<ContactExchangeCodeVO>(list);
        return new DhPageInfo<ContactExchangeCodeVO>(pageInfo, list);
    }

    /**
     * 开启关闭联系人发码
     * 联系人发码状态  0发码 1不发码
     * @return
     */
    @Override
    public Boolean updateContactcodeStatus(Integer contactcodeStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        SysParameterSetting sysParameterSetting = contactDbService.selectContactCodeStatus();
        sysParameterSetting.setContactCodeStatus(contactcodeStatus);
        sysParameterSetting.setUpdatePeopleId(userAccount.getAccountId());
        sysParameterSetting.setUpdateTm(new Date());
        return contactDbService.updateContactcodeStatus(sysParameterSetting);
    }

    /**
     * 商机-新增商机-通过客户id查询联系人列表
     *
     * @param customerId 客户id
     * @return
     */
    @Override
    public List<Contact> contactByCustomerIdList(String customerId) {
        List<Contact> contactList = contactDbService.contactByCustomerIdList(customerId);
        return contactList;
    }

    /**
     * 联系人-新增联系人--同一客户下联系人重名-->合并联系方式
     *
     * @param customerId    客户id
     * @param contactName   联系人姓名
     * @param contactNature 联系人性质  0企业联系人  1非企业联系人
     * @return
     */
    @Override
    public List<Contact> getContactName(String customerId, String contactName, String contactNature) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        return contactDbService.getContactName(customerId, contactName, contactNature, userAccount.getAccountId());
    }

    /**
     * 联系人详情--联系方式 开启/废止联系方式
     *
     * @param fzCustomerContactVO contactInformationId数组 联系方式id
     * @param fzCustomerContactVO abolishState 废止状态  1启动 2废止
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public Boolean updateAbolishStateById(FzCustomerContactVO fzCustomerContactVO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        ContactInformation contactInformation = new ContactInformation();
        contactInformation.setAbolishState(Integer.parseInt(fzCustomerContactVO.getAbolishState()));
        contactInformation.setUpdatePeopleId(userAccount.getAccountId());
        contactInformation.setUpdateTm(new Date());
        Boolean rs = false;
        //if(contactInformationId.contains(",")){
        //String[] contactInformationIds = contactInformationId.split(",");
        for (String informationId : fzCustomerContactVO.getContactInformationId()) {
            contactInformation.setContactInformationId(informationId);
            rs = contactInformationDbService.updateAbolishStateById(contactInformation);
        }
        //}else{
        //contactInformation.setContactInformationId(contactInformationId);
        //rs = contactInformationDbService.updateAbolishStateById(contactInformation);
        //}

        return rs;
    }


    /**
     * 联系人-新增联系人--同一客户下联系方式不能一样
     *
     * @param customerId         客户id
     * @param contactInformation 联系方式
     * @param contactNature      联系人性质  0企业联系人  1非企业联系人
     * @return
     */
    @Override
    public List<ContactInformationVO> getCustomerIdAndContactInformation(String customerId, String contactInformation, String contactNature) {
        return contactInformationDbService.getCustomerIdAndContactInformation(customerId, contactInformation, contactNature);
    }

    /**
     * 联系人-客户详情-联系人列表-跳转联系人详情
     *
     * @param customerId         客户id
     * @param contactInformation 联系方式
     * @param contactName        联系人姓名
     * @return
     */
    @Override
    public Contact getContactId(String customerId, String contactInformation, String contactName) {
        return contactDbService.getContactId(customerId, contactInformation, contactName);
    }

    /**
     * 商机-新增商机-过客户id查询联系人列表  分页
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<Contact> pageContactByCustomerIdList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<Contact> list = contactDbService.pageContactByCustomerIdList(customerId, "create_tm desc");
        PageInfo<Contact> pageInfo = new PageInfo<Contact>(list);
        return new DhPageInfo<Contact>(pageInfo, list);
    }

    /**
     * @param clueFollowQO 跟进参数
     * @return
     * @author wll
     * info 联系人管理-联系人列表-跟进
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addContactFollow(ClueFollowQO clueFollowQO) {
        ClueFollowServiceImpl clueFollowServiceImpl = new ClueFollowServiceImpl();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        ClueFollow clueFollow = clueFollowServiceImpl.getClueFollow(clueFollowQO, userAccount);
        //类别为拜访 陪访 添加拜访表里数据
        if (clueFollowQO.getFollowWay() == 2 || clueFollowQO.getFollowWay() == 6) {//2-拜访 6-陪访
            //新增拜访记录
            String clueVisitVecordid = insertClueVisitVecord(clueFollowQO, userAccount);
            clueFollow.setVisitRecordId(clueVisitVecordid);//线索拜访表id
        }

        clueFollow.setFollowSource(3);

        //热力值加  和跟进次数相加
        Contact contact = contactDbService.selectContactById(clueFollowQO.getContactId());
        CustomerContactPerson customerContactPerson = customerContactPersonDbService.isInsertCustomerContactPerson(contact.getCustomerId(), contact.getContactName(), contact.getContactInformation());


        Integer thermodynamicValue = contact.getThermodynamicValue();
        if (thermodynamicValue == null) {
            thermodynamicValue = 0;
        }
        //跟进次数+1
        Integer followUpTimes = contact.getFollowUpTimes();
        if (followUpTimes == null) {
            followUpTimes = 0;
        }
        //跟进方式  1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
        if (clueFollowQO.getFollowWay() != 0) {
            //拜访 10分  其他的5分
            if (clueFollowQO.getFollowWay() == 2) {
                thermodynamicValue += 10;
            } else {
                thermodynamicValue += 5;
            }

            followUpTimes += 1;

        }

        //向客户联系人表增加跟进次数
        if (customerContactPerson != null) {
            customerContactPerson.setFollowUpTimes(followUpTimes);
            customerContactPersonDbService.updateCustomerContactPerson(customerContactPerson);
        }

        contact.setThermodynamicValue(thermodynamicValue);
        contact.setFollowUpTimes(followUpTimes);
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        contactDbService.updateContact(contact);

        Boolean result = clueFollowDbService.addClueFollow(clueFollow);
        return result;

    }

    /**
     * 查询联系人里面有的行业
     *
     * @param bs   0管理端 1用户端
     * @param type industry 行业 province 地区
     * @return
     */
    @Override
    public List<IndustryAreaVO> selectIndustry(String bs, String type) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name = null;
        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if ("0".equals(bs)) {
            if (rs) {
                number = 0;
            } else {
                //普通管理员
                number = 1;
                name = userAccount.getCompanyId();
            }
        } else {
            //普通用户
            number = 2;
            name = userAccount.getAccountId();
        }
        if ("industry".equals(type)) {
            return contactDbService.selectIndustry(name, number);
        } else {
            return contactDbService.selectProvince(name, number);
        }

    }

    /**
     * 联系人列表-设置为常用联系人
     *
     * @param contactId  联系人id
     * @param topContact 常用联系人  0常用  1不常用
     * @return
     */
    @Override
    public Boolean setUpTopContact(String contactId, Integer topContact) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Contact contact = contactDbService.selectContactById(contactId);
        contact.setTopContact(topContact);
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        return contactDbService.updateContact(contact);
    }

    /**
     * 根据客户id查询联系人信息
     *
     * @param pageIndex  页码
     * @param pageSize   分页大小
     * @param sortName   排序列名字
     * @param sortOrder  排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<Contact> contactByCustIdList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<Contact> contactList = contactDbService.contactByCustomerIdList(customerId);
        PageInfo<Contact> pageInfo = new PageInfo<Contact>(contactList);
        return new DhPageInfo<Contact>(pageInfo, contactList);
    }


    /**
     * 新增拜访记录
     *
     * @param clueFollowQO 跟进类
     * @param userAccount  用户信息
     * @return
     */
    public String insertClueVisitVecord(ClueFollowQO clueFollowQO, UserAccount userAccount) {
        ClueVisitRecord clueVisitRecord = new ClueVisitRecord();
        clueVisitRecord.setClueVisitRecordId(UUID.randomUUID().toString().replaceAll("-", ""));
        if (clueFollowQO.getFollowWay() == 2) {
            clueVisitRecord.setType(1);//拜访
        } else {
            clueVisitRecord.setType(2);//陪访
        }

        clueVisitRecord.setVisitAddress(clueFollowQO.getVisitAddress());//===========拜访地址 类型为这个的时候 传这个参数
        clueVisitRecord.setAccompanyVisitPeople(clueFollowQO.getContactName());//拜访人or配方人
        clueVisitRecord.setContactInformation(clueFollowQO.getContactInformation());//联系电话
        //沟通时长（秒）
        if (clueFollowQO.getFollowWay() == 1) {
            clueVisitRecord.setCommunicationTime(clueFollowQO.getCommunicationTime());//沟通时长（秒） 页面秒
        } else {
            clueVisitRecord.setCommunicationTime(clueFollowQO.getCommunicationTime() * 60);//沟通时长（秒） 页面分钟
        }
        clueVisitRecord.setVisitDetail(clueFollowQO.getFollowDetail());//详情
        clueVisitRecord.setUploadId(clueFollowQO.getAccountUploadId());//电话账号附件id
        clueVisitRecord.setMinUploadId(clueFollowQO.getMinUploadId());//电话时长附件id
        clueVisitRecord.setDeleteStatus(Short.parseShort("0"));
        clueVisitRecord.setCreatePeopleId(userAccount.getAccountId());//创建人
        clueVisitRecord.setCreateTm(clueFollowQO.getFollowTm());//创建时间（跟进日期）
        clueVisitRecord.setUpdatePeopleId(userAccount.getAccountId());//更新人id
        clueVisitRecord.setUpdateTm(new Date());//更新时间
        //clueVisitRecord.setClueId(clueFollowQO.getClueId());//线索id
        clueVisitRecord.setClueId(clueFollowQO.getClueId());//线索id
        clueVisitRecord.setMainVisitor(clueFollowQO.getMainVisitor());//主拜访人
        clueVisitRecord.setAccompanyingPerson(clueFollowQO.getAccompanyingPerson());//陪访人
        clueVisitRecord.setCustomerId(clueFollowQO.getCustomerId());//客户id
        if (clueVisitRecordDbService.insertClueVisitVecord(clueVisitRecord) > 0) {
            return clueVisitRecord.getClueVisitRecordId();
        } else {
            return "";
        }
    }


    /**
     * @Description: 联系人报表折线图
     * @Param: [dateType] 1、本周-按天  2、本月-按天  3、上月-按天  4、近三月-按周  5、本季度-按周  6、本年度-按月
     * @Return: com.crm.model.vo.contactManager.ContactReportLineVO
     * @Author: lixq-f
     * @Date: 2021/4/16
     **/
    @Override
    public ContactReportLineVO getContactReportLine(Integer dateType, String bs) {

        if (Boolean.FALSE.equals(StatisticalPeriodEnum.containPeriod(dateType))) {
            throw new IllegalArgumentException("参数错误, dateType" + dateType);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        List<String> initTimes = getInitTime(dateType);
        Map<String, Integer> followMap = null;
        Map<String, Integer> contactMap = null;
        List<ContactStatisticsVO> followDataList = null;
        List<ContactStatisticsVO> contactDataList = null;
        if (StatisticalPeriodEnum.THIS_YEAR.getCode() == dateType) {
            //月统计
            followDataList = statisticsContactByMonth(FOLLOW_QUERY_TYPE, accountId);
            contactDataList = statisticsContactByMonth(CONTACT_QUERY_TYPE, accountId);
        } else {
            //获取统计日数据
            followDataList = statisticsContactByDay(dateType, FOLLOW_QUERY_TYPE, accountId);
            contactDataList = statisticsContactByDay(dateType, CONTACT_QUERY_TYPE, accountId);
        }

        if (!CollectionUtils.isEmpty(followDataList)) {
            followMap = followDataList.stream()
                    .collect(Collectors.toMap(ContactStatisticsVO::getTime, f -> Optional.ofNullable(f.getCount()).orElse(0)));
        }
        if (!CollectionUtils.isEmpty(contactDataList)) {
            contactMap = contactDataList.stream()
                    .collect(Collectors.toMap(ContactStatisticsVO::getTime,  c-> Optional.ofNullable(c.getCount()).orElse(0)));
        }

        List<Integer> followTimes = Lists.newArrayList();
        List<Integer> newContacts = Lists.newArrayList();
        for (String time : initTimes) {
            if (Objects.nonNull(followMap)) {
                Integer count = Optional.ofNullable(followMap.get(time)).orElse(0);
                followTimes.add(count);
            } else {
                followTimes.add(0);
            }
            if (Objects.nonNull(contactMap)) {
                Integer count = Optional.ofNullable(contactMap.get(time)).orElse(0);
                newContacts.add(count);
            } else {
                newContacts.add(0);
            }
        }

        ContactReportLineVO result = new ContactReportLineVO();
        result.setDataTimes(initTimes);
        result.setFollowTimes(followTimes);
        result.setNewContacts(newContacts);

        return result;
    }


    /**
     * 按天统计本周、本月每天跟进次数、新增联系人
     *
     * @param dateType
     * @param queryType followTimes、newContact
     * @return
     */
    private List<ContactStatisticsVO> statisticsContactByDay(int dateType, String queryType, String accountId) {

        //yyyy-MM-dd HH:mm:ss
        String startTime = null;
        String endTime = null;
        if (StatisticalPeriodEnum.THIS_WEEK.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtil.getTimesWeekMorning());
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }
        if (StatisticalPeriodEnum.THIS_MONTH.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtil.getTimesMonthMorning());
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }
        if (StatisticalPeriodEnum.LAST_MONTH.getCode() == dateType) {
            DateTime dateTime = DateUtils.lastMonth();
            startTime = DateUtil.formatDateTime(DateUtils.beginOfMonth(dateTime));
            endTime = DateUtil.formatDateTime(DateUtils.endOfMonth(dateTime));
        }
        if (StatisticalPeriodEnum.RECENTLY_THREE_MONTH.getCode() == dateType) {
            DateTime dateTime = DateUtils.offsetMonth(DateUtil.getSysDate(), -2);
            startTime = DateUtil.formatDateTime(DateUtils.beginOfMonth(dateTime));
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }
        if (StatisticalPeriodEnum.THIS_QUARTER.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtils.beginOfQuarter(DateUtil.getSysDate()));
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }

        if (FOLLOW_QUERY_TYPE.equals(queryType)) {
            return clueFollowDbService.statisticsFollowTimesByDay(startTime, endTime, accountId);
        }
        return contactDbService.statisticsNewContactByDay(startTime, endTime, accountId);
    }


    /**
     * 按月统计本年度跟进次数、新增联系人
     *
     * @return
     */
    private List<ContactStatisticsVO> statisticsContactByMonth(String queryType, String accountId) {
        int currentYear = DateUtils.getCurrentYear();
        if (FOLLOW_QUERY_TYPE.equals(queryType)) {
            return clueFollowDbService.statisticsFollowTimesByMonth(currentYear, accountId);
        }
        return contactDbService.statisticsNewContactByMonth(currentYear, accountId);
    }


    /**
     * 获取初始化时间-联系人折线图X轴 yyyy-MM-dd
     *
     * @param dateType
     * @return
     */
    private List<String> getInitTime(int dateType) {
        Date startDate = null;
        Date nowDate = DateUtil.getSysDate();
        if (StatisticalPeriodEnum.THIS_WEEK.getCode() == dateType) {
            startDate = DateUtil.getTimesWeekMorning();
            return DateUtils.getBetweenDateList(startDate, nowDate, DateUtils.DATE_FORMAT_YYYY_MM_DD, 1);
        }
        if (StatisticalPeriodEnum.THIS_MONTH.getCode() == dateType) {
            startDate = DateUtil.getTimesMonthMorning();
            return DateUtils.getBetweenDateList(startDate, nowDate, DateUtils.DATE_FORMAT_YYYY_MM_DD, 1);
        }
        if (StatisticalPeriodEnum.LAST_MONTH.getCode() == dateType) {
            DateTime dateTime = DateUtils.lastMonth();
            DateTime beginOfLastMonth = DateUtils.beginOfMonth(dateTime);
            DateTime endOfLastMonth = DateUtils.endOfMonth(dateTime);
            return DateUtils.getBetweenDateList(beginOfLastMonth, endOfLastMonth, DateUtils.DATE_FORMAT_YYYY_MM_DD, 1);
        }
        if (StatisticalPeriodEnum.RECENTLY_THREE_MONTH.getCode() == dateType) {
            DateTime dateTime = DateUtils.offsetMonth(DateUtil.getSysDate(), -2);
            DateTime startTime = DateUtils.beginOfMonth(dateTime);
            Date endTime = DateUtil.getSysDate();
            return DateUtils.getBetweenDateList(startTime, endTime, DateUtils.DATE_FORMAT_YYYY_MM_DD, 1);

        }
        if (StatisticalPeriodEnum.THIS_QUARTER.getCode() == dateType) {
            DateTime beginOfQuarter = DateUtils.beginOfQuarter(DateUtil.getSysDate());
            Date endOfQuarter = DateUtil.getSysDate();
            return DateUtils.getBetweenDateList(beginOfQuarter, endOfQuarter, DateUtils.DATE_FORMAT_YYYY_MM_DD, 1);

        }
        if (StatisticalPeriodEnum.THIS_YEAR.getCode() == dateType) {
            DateTime dateTime = DateUtils.beginOfYear(DateUtil.getSysDate());
            List<DateTime> dateTimes = DateUtils.rangeToList(dateTime, DateUtil.getSysDate(), DateField.MONTH);
            return dateTimes.stream().map(date -> DateUtil.formatDate(date, DateUtils.DATE_FORMAT_YYYY_MM))
                    .collect(Collectors.toList());
        }

        return null;
    }


    @Override
    public DhPageInfo<ContactReportListVO> getContactReportList(Integer pageIndex, Integer pageSize, String sortName,
                                                                String sortOrder, Integer dateType) {

        if (Boolean.FALSE.equals(StatisticalPeriodEnum.containPeriod(dateType))) {
            throw new IllegalArgumentException("参数错误, dateType: " + dateType);
        }

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        String startTime = null;
        String endTime = null;
        if (StatisticalPeriodEnum.THIS_WEEK.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtil.getTimesWeekMorning());
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }
        if (StatisticalPeriodEnum.THIS_MONTH.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtil.getTimesMonthMorning());
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }
        if (StatisticalPeriodEnum.LAST_MONTH.getCode() == dateType) {
            DateTime dateTime = DateUtils.lastMonth();
            startTime = DateUtil.formatDateTime(DateUtils.beginOfMonth(dateTime));
            endTime = DateUtil.formatDateTime(DateUtils.endOfMonth(dateTime));
        }
        if (StatisticalPeriodEnum.RECENTLY_THREE_MONTH.getCode() == dateType) {
            DateTime dateTime = DateUtils.offsetMonth(DateUtil.getSysDate(), -2);
            startTime = DateUtil.formatDateTime(DateUtils.beginOfMonth(dateTime));
            endTime = DateUtil.formatDateTime(DateUtil.getSysDate());
        }
        if (StatisticalPeriodEnum.THIS_QUARTER.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtils.beginOfQuarter(DateUtil.getSysDate()));
            endTime = DateUtil.formatDateTime(DateUtils.endOfQuarter(DateUtil.getSysDate()));
        }
        if (StatisticalPeriodEnum.THIS_YEAR.getCode() == dateType) {
            startTime = DateUtil.formatDateTime(DateUtils.beginOfYear(DateUtil.getSysDate()));
            endTime = DateUtil.formatDateTime(DateUtils.endOfYear(DateUtil.getSysDate()));
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        List<ContactReportListVO> contactReportList = clueFollowDbService.getContactReportList(accountId, startTime, endTime);
        PageInfo<ContactReportListVO> pageInfo = new PageInfo<>(contactReportList);
        return new DhPageInfo<ContactReportListVO>(pageInfo, contactReportList);
    }

    /**
     * 呼叫中心根据手机号和账号Id查询联系人
     *
     * @param contactInformation 联系方式
     * @param accountId          账号Id
     * @return {@link {com.crm.model.entity.contactManager.Contact}}
     * @Author pym
     * @Date 2021/6/11 15:35
     */
    @Override
    public Contact getContactByContactInfoAndId(String contactInformation, String accountId) {
        return contactDbService.getContactByContactInfoAndId(contactInformation, accountId);
    }

    /**
     * 导入联系人信息
     *
     * @param list      联系人信息集合
     * @param companyId 分公司id
     * @return
     */
    @Override
    public JSONObject importContact(List<ContactImportVO> list, String companyId) throws ParseException {
        //返回的结果集
        JSONObject jsonObject = new JSONObject();
        //导入数量
        int importNum = 0;
        //重复的行数
        String repeatIdStr = "";
        //失败行数
        String importFailIdStr = "";

        if (list.size() > 0){
            int count = 300;                   //一个线程处理300条数据
            int listSize = list.size();        //数据集合大小
            int runSize = (listSize/count)+1;  //开启的线程数
            //int runSize = importExportService.calculateImportedThreads(listSize);

            List<ContactImportVO> newlist = null;       //存放每个线程的执行数据

            ExecutorService executor = Executors.newCachedThreadPool();
            //创建两个个计数器
            CountDownLatch begin = new CountDownLatch(1);
            CountDownLatch end = new CountDownLatch(runSize);
            List<FutureTask<JSONObject>> taskList = new ArrayList<FutureTask<JSONObject>>();
            for (int i = 0; i < runSize ; i++) {
                //计算每个线程执行的数据
                if ((i + 1) == runSize) {
                    int startIndex = (i * count);
                    int endIndex = list.size();
                    newlist = list.subList(startIndex, endIndex);
                } else {
                    int startIndex = (i * count);
                    int endIndex = (i + 1) * count;
                    if (endIndex > list.size()){
                        endIndex = list.size();
                    }
                    newlist = list.subList(startIndex, endIndex);
                }
                FutureTask<JSONObject> futureTask = new FutureTask(new InsertContactCallable(contactDbService,customerPoolDbService,
                                                                                            contactInformationDbService,customerDbService,
                                                                                            userAccountDbService,importFailureLogDbService,
                                                                                            sysCompanyDbService,singleProductCustomerDbService,
                                                                                            singleProductCustomerContactDbService,
                                                                                            newlist, begin, end,companyId));
                taskList.add(futureTask);
                executor.submit(futureTask);//submit返回一个Future，代表了即将要返回的结果
            }
            //重复的行数
            List<Integer> repeatIdList = new ArrayList();
            //失败行数
            List<Integer> importFailIdList = new ArrayList();

            for (int i = 0; i < taskList.size(); i++) {
                try {
                    // FutureTask的get方法会自动阻塞,直到获取计算结果为止
                    //导入数量
                    importNum = importNum + taskList.get(i).get().getInteger("importNum");

                    //重复数量
                    JSONArray repeatIdArray = taskList.get(i).get().getJSONArray("repeatIdStr");
                    for (int j = 0; j < repeatIdArray.size(); j++){
                        int repeat = Integer.parseInt(repeatIdArray.get(j).toString());
                        repeatIdList.add(repeat + i*100);
                    }

                    //失败数量
                    JSONArray importFailIdArray = taskList.get(i).get().getJSONArray("importFailIdStr");
                    for (int j = 0; j < importFailIdArray.size(); j++){
                        int importFail = Integer.parseInt(importFailIdArray.get(j).toString());
                        importFailIdList.add(importFail + i*100);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            // 关闭线程池
            executor.shutdown();

            jsonObject.put("importCallNum", importNum);
            jsonObject.put("repeatIdStr", repeatIdList);
            jsonObject.put("importFailIdStr", importFailIdList);

        }
        return jsonObject;
    }

    @Override
    public List<ContactMyVO> selectMyContactsByContactId(String contactId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<ContactMyVO> contacts = new ArrayList<>();
        ContactMyVO contactMyVO = new ContactMyVO();
        Contact contact = contactDbService.selectContactById(contactId);
        BeanUtils.copyProperties(contact,contactMyVO);
            List<String> contactInformationIds = new ArrayList<String>();
            List<ContactInformation> contactInformation = contactInformationDbService.selectContactInformationByContactIdAndCompanyId(contact.getContactId(),userAccount.getAccountId(), userAccount.getCompanyId());
            if(contactInformation.size()>0){
                for (ContactInformation information : contactInformation) {
                    contactInformationIds.add(information.getContactInformation());
                }
            }
            contactMyVO.setContactDetails(contactInformationIds);
            contacts.add(contactMyVO);
        return contacts;
    }

    @Override
    public List<ContactMyVO> selectCustomerContacts(String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<Contact> contacts = contactDbService.selectMyContactsByCustomerId(customerId, userAccount.getAccountId(), userAccount.getCompanyId());

        List<ContactMyVO> contactMyVOS= new ArrayList<ContactMyVO>();
        contacts.stream().forEach(contact -> {
            ContactMyVO contactMyVO = new ContactMyVO();
            BeanUtils.copyProperties(contact,contactMyVO);
            //查询联系人联系方式
            List<String> contactInformationIds = new ArrayList<String>();
            List<ContactInformation> contactInformation = contactInformationDbService.selectContactInformationByContactIdAndCompanyId(contact.getContactId(),userAccount.getAccountId(),userAccount.getCompanyId());
            if(contactInformation.size()>0){
                for (ContactInformation information : contactInformation) {
                    contactInformationIds.add(information.getContactInformation());
                }
            }
            contactMyVO.setContactDetails(contactInformationIds);
            contactMyVOS.add(contactMyVO);
        });
        return contactMyVOS;
    }

    @Override
    public int comparisonData() {
        int i = 0;
        //String companyId = "9fa2dde1393311eb9e0a00163e08893d";
         String companyId = "8bbc6f5391b247758b71a0f6f5076fea";
        List<Contact> list = contactDbService.selectCompanyId(companyId,0);
        if(list != null && list.size() > 0){
            for(Contact contact : list) {
                CustomerContactPerson contactPerson = customerContactPersonDbService.selectCustomerContactPerson(contact.getCustomerId(),contact.getContactName(),contact.getContactInformation(),contact.getCompanyId());
                if(StringUtils.isBlank(contactPerson.getCustomerContactPersonId())) {
                    i+=1;
                    CustomerContactPerson customerContactPerson = new CustomerContactPerson();
                    customerContactPerson.setCustomerContactPersonId(CommonUtils.getGUID());
                    customerContactPerson.setContactName(contact.getContactName());
                    customerContactPerson.setContactPosition(contact.getContactPosition());
                    customerContactPerson.setContactInformation(contact.getContactInformation());
                    customerContactPerson.setMailBox(contact.getMailBox());
                    customerContactPerson.setWx(contact.getWx());
                    customerContactPerson.setCreatePeopleId(contact.getCreatePeopleId());
                    customerContactPerson.setCreateTm(contact.getCreateTm());
                    customerContactPerson.setUpdatePeopleId(contact.getUpdatePeopleId());
                    customerContactPerson.setUpdateTm(new Date());
                    customerContactPerson.setCustomerId(contact.getCustomerId());
                    customerContactPerson.setDataSource(1);
                    customerContactPerson.setCompanyId(contact.getCompanyId());
                    customerPoolDbService.addCustomerContactPerson(customerContactPerson);
                }
            }
        }
        System.out.println("------------"+i);
        System.out.println("成功");
        return i;
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public int updateRepeatData() {
        int a = 0;
        int b = 0;
        //String companyId = "9fa2dde1393311eb9e0a00163e08893d";
        String companyId = "8bbc6f5391b247758b71a0f6f5076fea";
        List<ContactRepeatVO> list = contactDbService.selectContactrepeat(companyId);
        if(list != null && list.size() > 0){
            for(ContactRepeatVO contact : list) {
                b = 0;
                List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountIdAndCompanyId(contact.getCustomerId(),contact.getContactName(),contact.getContactInformation(),"0",contact.getAccountId(),contact.getCompanyId(),"");
                if(contactList != null && contactList.size() > 0){
                    for(Contact con : contactList) {
                        b += 1;
                        List<CustomerContract> contractList = customerContractDbService.selectByContactId(con.getContactId());
                        if(contractList.size() == 0) {

                            if(b<contactList.size()) {
                                //联系人表
                                con.setUpdateTm(new Date());
                                con.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                                contactDbService.updateContact(con);

                                //联系人的联系方式表
                                ContactInformation contactInformation = new ContactInformation();
                                contactInformation.setContactId(con.getContactId());
                                contactInformation.setUpdateTm(new Date());
                                contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                                contactInformationDbService.updateInformation(contactInformation);

                                //客户下联系人
                                CustomerContactPerson contactPerson = customerContactPersonDbService.selectCustomerContactPerson(con.getCustomerId(),con.getContactName(),con.getContactInformation(),con.getCompanyId());
                                contactPerson.setUpdateTm(new Date());
                                contactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                                customerPoolDbService.updateCustomerContactPerson(contactPerson);
                                a+=1;
                            }
                        }
                    }
                }
            }
        }
        System.out.println("------------"+a);
        System.out.println("成功");
        return a;
    }

    @Override
    public int updateRepeatDatas() {
        int a = 0;
        //String companyId = "9fa2dde1393311eb9e0a00163e08893d";
        String companyId = "8bbc6f5391b247758b71a0f6f5076fea";
        List<ContactRepeatVO> list = customerContactPersonDbService.selectContactrepeat(companyId);
        if(list != null && list.size() > 0){
            for(ContactRepeatVO contact : list) {
                for(int i = 0; i<contact.getContactNum()-1; i++) {
                    CustomerContactPerson contactPerson = customerContactPersonDbService.selectCustomerContactPerson(contact.getCustomerId(),contact.getContactName(),contact.getContactInformation(),contact.getCompanyId());
                    contactPerson.setUpdateTm(new Date());
                    contactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                    customerPoolDbService.updateCustomerContactPerson(contactPerson);
                    a+=1;
                }
            }
        }
        System.out.println("------------"+a);
        System.out.println("成功");
        return a;
    }


    /**
     * 判断该客户下是否有此联系电话
     * @Author renshaorong
     * @Date 2021/10/21
     * @param customerId
     * @param contactPhone
     * @return true：有，false：没有
     */
    @Override
    public boolean checkExist(String customerId, String contactPhone) {
        return contactDbService.checkExist(customerId,contactPhone) > 0;
    }

    /**
     * 查询联系人里面有的标签
     * @param bs 0管理端 1用户端
     * @return
     */
    @Override
    public List<String> selectTag(String bs) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        String name = null;
        //number  0超管 1普通管理员  2普通用户
        Integer number = 0;
        if ("0".equals(bs)) {
            if (rs) {
                number = 0;
            } else {
                //普通管理员
                number = 1;
                name = userAccount.getCompanyId();
            }
        } else {
            //普通用户
            number = 2;
            name = userAccount.getAccountId();
        }
        return contactDbService.selectTag(name, number);
    }

    /**
     * 联系人列表--废止联系人 开启/废止联系方式    废止联系人,联系方式,客户下联系人
     * @param fz abolishState 废止状态  1启动 2废止
     * @return
     */
    @Override
    public Boolean updateContactAbolishState(FzCustomerContactVO fz) {

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        //废止联系人
        Contact contact = contactDbService.selectContactById(fz.getContactId());
        contact.setAbolishState(Integer.parseInt(fz.getAbolishState()));
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        contactDbService.updateAbolishStateById(contact);

        //废止联系方式    通过联系人id查询下面的联系方式
        List<ContactInformation> contactInformationList = contactInformationDbService.contactInformationList("create_tm desc",contact.getContactId());
        for(ContactInformation contactInformation : contactInformationList){
            contactInformation.setAbolishState(Integer.parseInt(fz.getAbolishState()));
            contactInformation.setUpdatePeopleId(userAccount.getAccountId());
            contactInformation.setUpdateTm(new Date());
            contactInformationDbService.updateAbolishStateById(contactInformation);
        }

        //客户下的联系人废止
        if(!StringUtils.isBlank(fz.getContactNature())) {
            if("0".equals(fz.getContactNature())) {
                List<CustomerContactPerson> custContactList = customerDbService.getCustomerIdAndContactName(contact.getCustomerId(), contact.getContactName(),contact.getContactInformation());
                if(custContactList.size()!= 0){
                    CustomerContactPerson customerContactPerson = custContactList.get(0);
                    customerContactPerson.setAbolishState(Integer.parseInt(fz.getAbolishState()));
                    customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                    customerContactPerson.setUpdateTm(new Date());
                    customerPoolDbService.updateAbolishStateById(customerContactPerson);
                }
            }
        }
        return true;
    }

    /**
     * 新增跟进计划时间
     * @param qo
     * @return
     */
    @Override
    public Boolean addContactFollowPlanTimes(ContactFollowPlanTimeQO qo) {
        if(qo.getContactIds().size() == 0) {
            return false;
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        qo.setUpdatePeopleId(userAccount.getAccountId());
        qo.setFollowPlanTime(qo.getFollowPlanTime());
        qo.setUpdateTm(new Date());
        return contactDbService.addContactFollowPlanTimes(qo);
    }

    /**
     * 修改跟进计划时间
     */
    @Override
    public void updateContactFollowPlanTime() {
        //UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String date = df.format(new Date());
        List<Contact> list = contactDbService.selectLessDayFollowPlanTime(date);
        for(Contact contact : list) {
            //contact.setUpdatePeopleId(userAccount.getAccountId());
            contact.setFollowPlanTime(null);
            contact.setUpdateTm(new Date());
            contactDbService.updateContactFollowPlanTime(contact);
        }
    }

    /**
     * 修改联系人意向状态
     * @param contactId 联系人id
     * @param currentIntention 目前意向   0有意向 1无意向
     * @return
     */
    @Override
    public Boolean updateContactCurrentIntention(String contactId, String currentIntention) {
        Contact contact = new Contact();
        contact.setContactId(contactId);
        contact.setCurrentIntention(currentIntention);
        return contactDbService.updateContact(contact);
    }

    /**
     * 移除计划
     * @param contactId 联系人id
     * @return
     */
    @Override
    public Boolean updateFollowPlanTime(String contactId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Contact contact = new Contact();
        contact.setContactId(contactId);
        contact.setFollowPlanTime(null);
        contact.setUpdateTm(new Date());
        return contactDbService.updateContactFollowPlanTime(contact);
    }


}
